import World from "./world/World";
import PlayerSnake from "./snake/PlayerSnake";
import EventDispatcher from "../core/EventDispatcher";
import { GameEvent } from "./event/GameEvent";

const et = GameEvent.Type

export default class Game {

    /** 上一时间，用于计算dt */
    private _last = Date.now()
    /** 帧间隔时间 单位s */
    private _dt = 0;
    /** 游戏逻辑帧率 */
    private _fps = 30
    /** 世界实例 */
    private _world = new World(this)
    /** 事件派发器 */
    private _ed = new EventDispatcher<GameEvent.Def>()
    /** 暂停状态 */
    private _isPause = false

    /** 初始化 */
    start() {
        this._world.start()
        //开启游戏逻辑
        setInterval(() => {
            let now = Date.now()
            this._dt = (now - this._last) / 1000
            this._last = now
            this.update()
        }, 1000 / this._fps)
    }

    /** 每帧执行 */
    update() {
        if (!this._isPause) {
            this._world.update()
            this._ed.send(et.GAME_UPDATE, { game: this })
        }
    }

    /** 加入游戏 */
    join(name: string): PlayerSnake {
        //添加到世界
        let snake = new PlayerSnake({ world: this._world, name })
        this._world.addSnake(snake)
        snake.spawn()
        return snake
    }

    /** 退出游戏 */
    exit(id: number) {
        //从世界移除
        this._world.removeSnake(id)
    }

    /** 暂停 */
    set pause(v: boolean) {
        this._isPause = v
    }

    // ================================================================

    /** 帧间隔时间 单位s */
    get dt() { return this._dt }

    /** 世界实例 */
    get world() { return this._world }

    /** 事件派发器 */
    get ed() { return this._ed }
}